package com.ruoyi.course.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.course.domain.CdCourseMessage;
import com.ruoyi.course.domain.CdCourseTeacher;
import com.ruoyi.course.service.ICdCourseMessageService;
import com.ruoyi.course.service.ICdCourseTeacherService;
import com.ruoyi.course.utils.RoleUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.course.mapper.CdStudentTeacherCourseMapper;
import com.ruoyi.course.domain.CdStudentTeacherCourse;
import com.ruoyi.course.service.ICdStudentTeacherCourseService;
import org.springframework.web.multipart.MultipartFile;

/**
 * studentcourseService业务层处理
 * 
 * @author ruoyi
 * @date 2023-12-18
 */
@Service
@Slf4j
public class CdStudentTeacherCourseServiceImpl implements ICdStudentTeacherCourseService 
{
    @Autowired
    private CdStudentTeacherCourseMapper cdStudentTeacherCourseMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ICdCourseMessageService cdCourseMessageService;

    @Autowired
    private ICdCourseTeacherService cdCourseTeacherService;

    @Autowired
    private RoleUtils roleUtils;

    /**
     * 查询studentcourse
     * 
     * @param teacherId studentcourse主键
     * @return studentcourse
     */
    @Override
    public List<CdStudentTeacherCourse> selectCdStudentTeacherCourseByTeacherId(Long teacherId)
    {
        return cdStudentTeacherCourseMapper.selectCdStudentTeacherCourseByTeacherId(teacherId);
    }

    /**
     * 查询studentcourse列表
     * 
     * @param cdStudentTeacherCourse studentcourse
     * @return studentcourse
     */
    @Override
    public List<CdStudentTeacherCourse> selectCdStudentTeacherCourseList(CdStudentTeacherCourse cdStudentTeacherCourse)
    {
        // 查询学生选课信息（根据student_id,teacher_id,course_id联查）
        // 系主任\教师：查看所有  学生：只查看自己
        if (roleUtils.isStudent()) {
            cdStudentTeacherCourse.setStudentId(SecurityUtils.getUserId());
        }
        List<CdStudentTeacherCourse> list = cdStudentTeacherCourseMapper.selectCdStudentTeacherCourseList(cdStudentTeacherCourse);
        for (CdStudentTeacherCourse entity : list) {
            SysUser student = sysUserService.selectUserById(entity.getStudentId());
            entity.setStudentUserName(student.getUserName());
            entity.setStudentNickName(student.getNickName());

            SysUser teacher = sysUserService.selectUserById(entity.getTeacherId());
            entity.setTeacherUserName(teacher.getUserName());
            entity.setTeacherNickName(teacher.getNickName());

            CdCourseMessage cdCourseMessage = cdCourseMessageService.selectCdCourseMessageByCourseId(entity.getCourseId());
            entity.setCourseName(cdCourseMessage.getCourseName());
        }

        return list;
    }

    /**
     * 新增studentcourse
     * 
     * @param cdStudentTeacherCourse studentcourse
     * @return 结果
     */
    @Override
    public int insertCdStudentTeacherCourse(CdStudentTeacherCourse cdStudentTeacherCourse)
    {
        return cdStudentTeacherCourseMapper.insertCdStudentTeacherCourse(cdStudentTeacherCourse);
    }

    /**
     * 修改studentcourse
     * 
     * @param cdStudentTeacherCourse studentcourse
     * @return 结果
     */
    @Override
    public int updateCdStudentTeacherCourse(CdStudentTeacherCourse cdStudentTeacherCourse)
    {
        return cdStudentTeacherCourseMapper.updateCdStudentTeacherCourse(cdStudentTeacherCourse);
    }

    /**
     * 批量删除studentcourse
     * 
     * @param teacherIds 需要删除的studentcourse主键
     * @return 结果
     */
    @Override
    public int deleteCdStudentTeacherCourseByTeacherIds(Long[] teacherIds)
    {
        return cdStudentTeacherCourseMapper.deleteCdStudentTeacherCourseByTeacherIds(teacherIds);
    }

    /**
     * 删除studentcourse信息
     * 
     * @param teacherId studentcourse主键
     * @return 结果
     */
    @Override
    public int deleteCdStudentTeacherCourseByTeacherId(Long teacherId)
    {
        return cdStudentTeacherCourseMapper.deleteCdStudentTeacherCourseByTeacherId(teacherId);
    }

    /**
     * 导入学生选课信息（关联 学生-教师-课程）
     * @param file
     */
    @Override
    public void importData(MultipartFile file) {
        ExcelUtil<CdStudentTeacherCourse> util = new ExcelUtil<>(CdStudentTeacherCourse.class);
        try {
            @Cleanup
            InputStream inputStream = file.getInputStream();
            List<CdStudentTeacherCourse> list = util.importExcel(inputStream);

            for (CdStudentTeacherCourse entity : list) {
                String studentUserName = entity.getStudentUserName();
                String teacherUserName = entity.getTeacherUserName();
                String courseName = entity.getCourseName();

                if (studentUserName == null) {
                    log.error("学号不能为空");
                    continue;
                }
                if (teacherUserName == null) {
                    log.error("工号不能为空");
                    continue;
                }
                if (courseName == null) {
                    log.error("课程名不能为空");
                    continue;
                }

                SysUser student = sysUserService.selectUserByUserName(studentUserName);
                if (student == null) {
                    log.error("学生不存在，请核对学号是否正确");
                    continue;
                }

                Long courseId = cdCourseMessageService.selectCdCourseMessageByCourseName(courseName);
                if (courseId == null) {
                    log.error("课程名错误，该课程在课程表中不存在");
                    continue;
                }

                SysUser teacher = sysUserService.selectUserByUserName(teacherUserName);
                if (teacher == null) {
                    log.error("教师不存在，请核对工号是否正确");
                    continue;
                }
                CdCourseTeacher cdCourseTeacher = cdCourseTeacherService.selectCdCourseTeacherByTeacherIdAndCourseId(teacher.getUserId(), courseId);
                if (cdCourseTeacher == null) {
                    log.error("该教师不指导这门课程");
                    continue;
                }
                if (!courseId.equals(cdCourseTeacher.getCourseId())) {
                    log.error("该教师不指导这门课程");
                    continue;
                }

                entity.setTeacherId(teacher.getUserId());
                entity.setStudentId(student.getUserId());
                entity.setCourseId(courseId);
                List<CdStudentTeacherCourse> hasContain = cdStudentTeacherCourseMapper.selectCdStudentTeacherCourseList(entity);
                if (!hasContain.isEmpty()) {
                    log.error("导入重复数据");
                    continue;
                }

                CdStudentTeacherCourse cdStudentTeacherCourse = new CdStudentTeacherCourse();
                cdStudentTeacherCourse.setCourseId(courseId);
                cdStudentTeacherCourse.setStudentId(student.getUserId());
                cdStudentTeacherCourse.setTeacherId(teacher.getUserId());
                cdStudentTeacherCourseMapper.insertCdStudentTeacherCourse(cdStudentTeacherCourse);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 老师查看自己指导的课程
     * @return
     */
    @Override
    public List<CdCourseMessage> listByTeacherSelf() {
        if (!roleUtils.isTeacher()) {
            log.error("你的身份不是老师，无法查看");
        }
        List<CdStudentTeacherCourse> courseList = cdStudentTeacherCourseMapper.selectCdStudentTeacherCourseByTeacherId(SecurityUtils.getUserId());
        Set<Long> courseIds = new HashSet<>();
        for (CdStudentTeacherCourse cdStudentTeacherCourse : courseList) {
            courseIds.add(cdStudentTeacherCourse.getCourseId());
        }

        List<CdCourseMessage> list = new ArrayList<>();
        for (Long courseId : courseIds) {
            CdCourseMessage cdCourseMessage = cdCourseMessageService.selectCdCourseMessageByCourseId(courseId);
            list.add(cdCourseMessage);
        }

        return list;
    }

    @Override
    public Set<Long> listByStudentSelf(Long studentId) {
        return cdStudentTeacherCourseMapper.listByStudentSelf(studentId);
    }
}
